package com.jtcoding.chat.advice;

import com.jtcoding.chat.exception.ApiException;
import com.jtcoding.chat.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author jason.tang
 * @create 2019-02-15 14:39
 * @description 监控Controller层Api异常
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.jtcoding.chat.controller"})
public class ApiExceptionAdvice {

    /**
     * 捕获自定义ApiException异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ApiException.class)
    private Result apiExceptionHandler(ApiException exception) {
        if (exception.getResultCode() == null) {
            log.error("ApiExceptionAdvice Error:", exception);
            return Result.failure(exception.getMessage());
        }
        log.error("ApiExceptionAdvice Error:", exception.getResultCode());
        return Result.failure(exception.getResultCode());
    }

    /**
     * 处理其他运行时异常
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    private Result exceptionHandler(Exception exception) {
        log.error("ApiExceptionAdvice Error:", exception);
        return Result.failure(exception.getMessage());
    }

}